module PFD(
	count_clk,		//clock for counter, assumed to be 32-bit
	ref_clk,			//reference clock from HDMI signal, 15Hz
	motor_clk,		//feedback pulses from motor, 15Hz closed-loop
	count_out		//32-bit output of counter
	);
	
	input count_clk;
	input ref_clk;
	input motor_clk;
	
	output reg [15:0] count_out;
	
	reg [15:0] count;
	reg [15:0] ncount;
	
	reg cref_clk;
	reg nref_clk;
	
	always@(posedge count_clk) begin
		count <= ncount;
		cref_clk <= nref_clk;
	end
	
	always@(count or cref_clk or ref_clk) begin
		if(cref_clk == 1'b1 && ref_clk == 1'b0) begin
			ncount = 16'd0;
		end
		else begin
			ncount = count + 1;
		end
			
		nref_clk = ref_clk;
	end
	
	always@(negedge motor_clk) begin
		count_out <= ncount;
	end
	
	initial begin
		count = 32'd0;
		ncount = 32'd0;
	end
	
endmodule